package com.bjpowernode.crm.workbench.web.controller;

import com.bjpowernode.crm.commons.Activities;
import com.bjpowernode.crm.commons.Constant;
import com.bjpowernode.crm.commons.utils.DateUtils;
import com.bjpowernode.crm.commons.utils.Result;
import com.bjpowernode.crm.commons.utils.UUIDUtils;
import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.workbench.domain.Activity;
import com.bjpowernode.crm.workbench.domain.ActivityRemark;
import com.bjpowernode.crm.workbench.service.ActivityService;
import com.bjpowernode.crm.workbench.service.UserService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.security.pkcs11.wrapper.Constants;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: ActivityController<br/>
 * Package: com.bjpowernode.crm.workbench.web.controller<br/>
 * Description: <br/>
 * Date: 2022/7/6 14:47<br/>
 * Auther:对的我写的，错的我同事写的<br/>
 */
@Controller
public class ActivityController {

    @Resource
    private ActivityService activityService;
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping("/workbench/activity/index.do")
    public String gotoIndexPage()
    {
        return "workbench/activity/index";
    }

    @RequestMapping("/workbench/activity/queryActivities.do")
    @ResponseBody
    public Object queryActivities(@RequestParam(value ="name",required = false)String name,
                                  @RequestParam(value ="owner",required = false)String owner,
                                  @RequestParam(value ="startDate",required = false)String startDate,
                                  @RequestParam(value ="endDate",required = false)String endDate,
                                  @RequestParam(value ="pageNum",required = true)Integer pageNum,
                                  @RequestParam(value ="pageSize",required = true)Integer pageSize)
    {
        Map requestMap = new HashMap();
        requestMap.put("name",name);
        requestMap.put("owner",owner);
        requestMap.put("startDate",startDate);
        requestMap.put("endDate",endDate);
        requestMap.put("pageNum",(pageNum-1)*pageSize);
        requestMap.put("pageSize",pageSize);
       Activities<Activity> activities =  activityService.queryActivities(requestMap);
       Map<String,Object> resultMap = new HashMap();
       resultMap.put("activityList",activities.getActivityList());
       resultMap.put("allCount",activities.getAllCount());
       resultMap.put("allPages",activities.getAllCount()%pageSize==0 ? activities.getAllCount()/pageSize : activities.getAllCount()/pageSize+1);
       return resultMap;
    }

    @RequestMapping("/workbench/activity/openaddActivity.do")
    @ResponseBody
    public Object openaddActivity()
    {
        BoundListOperations operations = redisTemplate.boundListOps("userList");
        List<User> userList = operations.range(0, -1);
        if(null == userList || userList.size() ==0)
        {
            userList = userService.openaddActivity();
            for(User user : userList)
            {
                operations.leftPush(user);
            }
            operations.expire(DateUtils.getRemainSecondsOneDay(new Date()), TimeUnit.SECONDS);
        }
       return userList;
    }

    @RequestMapping("/workbench/activity/addActivities.do")
    @ResponseBody
    public Object addActivities(Activity activity, HttpServletRequest request)
    {
        activity.setId(UUIDUtils.getUUID());
        User user = (User) request.getSession().getAttribute(Constant.SESSION);
        activity.setCreateBy(user.getId());
        activity.setCreateTime(DateUtils.formatDateTime(new Date()));
        try {
            Integer count = activityService.addActivities(activity);
            if(count != 1)
            {
                return Result.fail("添加失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("添加失败！");
        }
        return Result.success();
    }

    @RequestMapping("/workbench/activity/editActivityModal.do")
    @ResponseBody
    public Object editActivityModal(@RequestParam(value = "id")String id)
    {
        Map map = new HashMap();
        List<User> userList = userService.openaddActivity();
        map.put("users",userList);
        Activity activity = activityService.queryActivityById(id);
        map.put("activity",activity);
        return map;
    }

    @RequestMapping("/workbench/activity/updateActivityModal.do")
    @ResponseBody
    public Object updateActivityModal(HttpServletRequest request,Activity activity)
    {
       User user = (User) request.getSession().getAttribute(Constant.SESSION);
       activity.setEditTime(DateUtils.formatDateTime(new Date()));
       activity.setEditBy(user.getId());
        try {
            Integer count =  activityService.updateActivityModal(activity);
            if(count != 1)
            {
                return Result.fail("更新失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("更新失败!");
        }
        return Result.success();
    }

    @ResponseBody
    @RequestMapping("/workbench/activity/deleteActivityBtn.do")
    private Object deleteActivityBtn(@RequestParam(value = "id")String[] ids)
    {
        try {
            Integer count = activityService.deleteActivityBtn(ids);
            if(count != ids.length)
            {
                return Result.fail("删除失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("删除失败！");
        }
        return Result.success();
    }

    @RequestMapping("/exportActivityAllBtn.do")
    public void exportActivityAllBtn(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        HSSFWorkbook wb =new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        HSSFCell cell1 = row.createCell(1);
        HSSFCell cell2 = row.createCell(2);
        HSSFCell cell3 = row.createCell(3);
        HSSFCell cell4 = row.createCell(4);
        cell.setCellValue("名称");
        cell1.setCellValue("所有者");
        cell2.setCellValue("开始日期");
        cell3.setCellValue("结束日期");
        cell4.setCellValue("成本");
        List<Activity> activityList = activityService.selectActivities();
        Activity activity=null;
        for(int i=0;i<activityList.size();i++)
        {
            activity=activityList.get(i);
            HSSFRow row1 = sheet.createRow(i+1);
            HSSFCell cell01 = row1.createCell(0);
            HSSFCell cell02 = row1.createCell(1);
            HSSFCell cell03 = row1.createCell(2);
            HSSFCell cell04 = row1.createCell(3);
            HSSFCell cell05 = row1.createCell(4);
            cell01.setCellValue(activity.getName());
            cell02.setCellValue(activity.getOwner());
            cell03.setCellValue(activity.getStartDate());
            cell04.setCellValue(activity.getEndDate());
            cell05.setCellValue(activity.getCost());
        }
        //设置中文文件名称
        String fileName = URLEncoder.encode("市场活动列表","UTF-8");
        //浏览器默认服务器传过去的是html，不是excel文件
        //设置响应类型:传输内容是流，并支持中文
        response.setContentType("application/octet-stream;charset=UTF-8");
        //设置响应头信息header，下载时以文件附件下载
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xls");
        //输出流对象
        OutputStream os = response.getOutputStream();
        wb.write(os);
        //强制刷新
        os.flush();
        os.close();
        wb.close();
    }

    @RequestMapping("/exportActivityXzBtn.do")
    public void exportActivityAllBtn(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "id")String[] ids) throws Exception
    {
        HSSFWorkbook wb =new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        HSSFCell cell1 = row.createCell(1);
        HSSFCell cell2 = row.createCell(2);
        HSSFCell cell3 = row.createCell(3);
        HSSFCell cell4 = row.createCell(4);
        cell.setCellValue("名称");
        cell1.setCellValue("所有者");
        cell2.setCellValue("开始日期");
        cell3.setCellValue("结束日期");
        cell4.setCellValue("成本");
        List<Activity> activityListbyids = activityService.selectActivities(ids);
        Activity activity;
        for(int i=0;i<activityListbyids.size();i++)
        {
            activity=activityListbyids.get(i);
            activity.getStartDate();
            activity.getEndDate();
            HSSFRow row1 = sheet.createRow(i+1);
            HSSFCell cell01 = row1.createCell(0);
            HSSFCell cell02 = row1.createCell(1);
            HSSFCell cell03 = row1.createCell(2);
            HSSFCell cell04 = row1.createCell(3);
            HSSFCell cell05 = row1.createCell(4);
            cell01.setCellValue(activity.getName());
            cell02.setCellValue(activity.getOwner());
            cell03.setCellValue(activity.getStartDate());
            cell04.setCellValue(activity.getEndDate());
            cell05.setCellValue(activity.getCost());
        }
        //设置中文文件名称
        String fileName = URLEncoder.encode("市场活动列表","UTF-8");
        //浏览器默认服务器传过去的是html，不是excel文件
        //设置响应类型:传输内容是流，并支持中文
        response.setContentType("application/octet-stream;charset=UTF-8");
        //设置响应头信息header，下载时以文件附件下载
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xls");
        //输出流对象
        OutputStream os = response.getOutputStream();
        wb.write(os);
        //强制刷新
        os.flush();
        os.close();
        wb.close();
    }

    @RequestMapping("/importActivityListBtn")
    @ResponseBody
    public Object importActivityListBtn(MultipartFile activityForm,HttpServletRequest request)
    {
        User user = (User) request.getSession().getAttribute(Constant.SESSION);
        try {
            HSSFWorkbook wb = new HSSFWorkbook(activityForm.getInputStream());
            HSSFSheet sheet = wb.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            Activity activity =null;
            List<Activity> activityList = new ArrayList<>();
            for(int i=1;i<=lastRowNum;i++)
            {
                activity =new Activity();
                HSSFRow row = sheet.getRow(i);
                HSSFCell cell01 = row.getCell(0);
                HSSFCell cell02 = row.getCell(1);
                HSSFCell cell03 = row.getCell(2);
                HSSFCell cell04 = row.getCell(3);
                HSSFCell cell05 = row.getCell(4);
                String name = cell01.getStringCellValue();
                String owner = cell01.getStringCellValue();
                String startDate = cell01.getStringCellValue();
                String endDate = cell01.getStringCellValue();
                String cost = cell01.getStringCellValue();
                activity.setCreateTime(DateUtils.formatDateTime(new Date()));
                activity.setId(UUIDUtils.getUUID());
                activity.setCreateBy(user.getId());
                activity.setName(name);
                activity.setOwner(owner);
                activity.setStartDate(startDate);
                activity.setEndDate(endDate);
                activity.setCost(cost);
                activityList.add(activity);

            }
            Integer count = activityService.addActivitiesByList(activityList);
            if(count !=activityList.size())
            {
                return Result.fail("上传失败！");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("上传失败！");
        }
        return Result.success();
    }

    @RequestMapping("/todetail.do")
    public String todetail(String id,HttpServletRequest request)
    {
        Activity activity = activityService.queryById(id);
        request.setAttribute("activity",activity);
        return "workbench/activity/detail";
    }
    @RequestMapping("/getbeizhudeneirong.do")
    @ResponseBody
    public Object getbeizhudeneirong(String activityId)
    {
        List<ActivityRemark> remarks = activityService.selectActivityRemark(activityId);
        return remarks;
    }

    @RequestMapping("/saveCreateRemark.do")
    @ResponseBody
    public Object saveCreateRemark(ActivityRemark remark,HttpServletRequest request)
    {
        try {
            User user = (User) request.getSession().getAttribute(Constant.SESSION);
            remark.setCreateBy(user.getId());
            remark.setCreateTime(DateUtils.formatDateTime(new Date()));
            remark.setId(UUIDUtils.getUUID());
            Integer count = activityService.insertbeizhu(remark);
            if(count !=1)
            {
                return Result.fail("添加失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("添加失败！");
        }
        return Result.success();
    }
    @RequestMapping("/openPages.do")
    @ResponseBody
    public Object openPages(ActivityRemark remark,HttpServletRequest request)
    {
        User user = (User) request.getSession().getAttribute(Constant.SESSION);
        try {
            remark.setEditBy(user.getId());
            remark.setEditTime(DateUtils.formatDateTime(new Date()));
            Integer count = activityService.updateactivityRemark(remark);
            if(count != 1)
            {
                return Result.fail("更新失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("更新失败！");
        }
        return Result.success();
    }

    @RequestMapping("/deleteRemark.do")
    @ResponseBody
    public Object deleteRemark(String id)
    {
        try {
            Integer count = activityService.deleteActivityRemarkById(id);
            if(count != 1)
            {
                return Result.fail("删除失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("删除失败！");
        }
        return Result.success();
    }


}
